<template>
  <div class="home">
    <van-swipe
      class="my-swipe"
      :autoplay="3000"
      indicator-color="white"
    >
      <van-swipe-item
        v-for="(item, index) in bannerList"
        :key="index"
        lazy-render
        @click="url(item)"
      >
        <img :src="item.tpic">
      </van-swipe-item>
    </van-swipe>
    <!-- <wx-open-launch-weapp
      id="launch-btn"
      username="gh_25e071b83ee0"
      path="pages/watch/index.html?living_code=OmOSx4B9pQ0n0sI3xZpFK9MN30IhT6NLGpWqSglRtp4">
      <div v-is="'script'" type="text/wxtag-template" style="display: block">
        <button class="btn">打开小程序</button>
      </div>
    </wx-open-launch-weapp> -->
    <van-sticky z-index="9">
      <div class="pub_tab">
        <div class="TabbarSlide_head">
          <div class="tabbarW">
            <van-tabs
              v-model:active="form.type"
              @click-tab="onClickTab"
              animated
              sticky
              :line-height="8"
              title-active-color="#12142E"
              title-inactive-color="#454757"
              color="#FF7A1F"
              background="#f7f7f7"
            >
              <van-tab
                :title="item.name"
                v-for="(item, index) in type "
                :key="index"
              />
            </van-tabs>
          </div>
          <!-- <div class="calendar">
            <svg
              class="calendar_svg"
              aria-hidden="true"
            >
              <use xlink:href="#icon-gengduo" />
            </svg>
          </div>-->
        </div>
      </div>
    </van-sticky>

    <van-pull-refresh
      disabled
      v-model="refreshing"
      @refresh="onRefresh"
    >
      <van-list
        v-model:loading="loading"
        :finished="finished"
        @load="loadMore"
        :immediate-check="false"
      >
        <div
          class="content_box"
          v-if="data.length > 0"
        >
          <div
            v-for="(item, index) in data"
            :key="index"
            @click="news(item.id)"
          >
            <div
              class="flex_box"
              @click="infodetail(item.id)"
              v-if="item.type !== 1"
            >
              <div class="mation_box">
                <div v-if="item.morepic">
                  <img :src="item.morepic">
                </div>
                <p class="van-multi-ellipsis--l2 fontBold content3 color1">
                  <van-tag
                    v-if="item.is_top"
                    style="height:18px;width:42px;justify-content: center;"
                    color="#FF7A1F"
                    type="primary"
                  >
                    精选
                  </van-tag>
                  {{ item.title }}
                </p>
              </div>
              <div class="time_box font400 content2 color6">
                <div>
                  <span class="time">{{ item.create_time }}</span>
                </div>
                <div class="iconSvgBox">
                  <svg
                    class="iconSvg"
                    aria-hidden="true"
                    v-if="item.is_sign == 0"
                  >
                    <use xlink:href="#icon-dianzan1" />
                  </svg>
                  <svg
                    class="iconSvg"
                    aria-hidden="true"
                    v-if="item.is_sign == 1"
                  >
                    <use xlink:href="#icon-dianzan2" />
                  </svg>
                  <span class="conut">{{ item.sign_num }}</span>
                </div>
              </div>
            </div>
            <img
              v-if="item.type == 1"
              class="newsImg"
              src="@/assets/img/banner2.png"
            >
          </div>
        </div>
      </van-list>
    </van-pull-refresh>
  </div>
  <!-- <RegisterTisp :reg-visible="regVisible" @closeDialog="closeDialog" :user-id="userId" /> -->
</template>

<script setup lang="ts">
// import wx from 'weixin-js-sdk'
import { getToken } from '@/service/cookie'
import { ref, computed, watch, onUnmounted } from 'vue'
import { homeNews, getBanner } from '@/api/index'
// import RegisterTisp from '@/components/RegisterTisp/index.vue'
import { useRouter, useRoute } from 'vue-router'
import emiter from '@/service/mitt'

// import mitt from 'mitt'
const router = useRouter()
const route = useRoute()
const userId: any = getToken('userId') || false
const regVisible: any = ref(false)
const loading: any = ref(false)
const finished: any = ref(false)
const refreshing: any = ref(false)
const bannerList: any = ref([])
const data: any = ref([])
const form: any = ref({
  page: 1,
  pageSize: 10,
  title: '',
  type: 0
})
console.log(getToken('bindId') === 'undefined', Number(getToken('bindId')))
if (userId) {
  regVisible.value = false
} else {
  if (sessionStorage.getItem('temporary') === '1') {
    regVisible.value = false
  } else {
    regVisible.value = true
  }
}

// const props = withDefaults(defineProps<{
//   jumpAppletSrc: string,
//   jumpAppletId: string
// }>(), {
//   jumpAppletId: 'launchBtn'
// })
// const emit = defineEmits(['jumpApplet'])

// onMounted(() => {
//   const btn: any = document.getElementById(props.jumpAppletId)
//   btn.addEventListener('launch', (e: any) => {
//     if (e.detail) {
//       emit('jumpApplet')
//     }
//   })
// })

onUnmounted(() => {
  regVisible.value = false
  emiter.off('like')
})

// const getWxApiTicket = async () => {
//   console.log('dddd', window.location.href.split('#')[0])
//   const res:any = await wechatJsapi({ url: window.location.href.split('#')[0] })
//   console.log('res', res)
//   wx.config({
//     beta: true, // 必须这么写，否则wx.invoke调用形式的jsapi会有问题
//     // debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
//     appId: res.appId, // 必填，企业微信的corpID，必须是本企业的corpID，不允许跨企业使用
//     timestamp: res.timestamp, // 必填，生成签名的时间戳
//     nonceStr: res.nonceStr, // 必填，生成签名的随机串
//     signature: res.signature, // 必填，签名，见 附录-JS-SDK使用权限签名算法
//     jsApiList: ['openLocation', 'chooseImage', 'previewImage'], // 必填，需要使用的JS接口列表
//     openTagList: ['wx-open-launch-weapp'] // 可选，需要使用的开放标签列表，例如['wx-open-launch-app']
//     // debug: false,
//     // appId: res.appId,
//     // timestamp: res.timestamp,
//     // nonceStr: res.nonceStr,
//     // signature: res.signature,
//     // beta: true,
//     // jsApiList: ['scanQRCode', 'chooseInvoiceTitle']
//   })
//   wx.ready(function () {
//   })
// }

// getWxApiTicket()

const type: any = ref([
  {
    name: '全部'
  },
  {
    name: '行业'
  },
  {
    name: '协会'
  },
  {
    name: '政策'
  }
])

const selectedDemandTypeId = computed(() => {
  return route.query.type || 0
})

watch(selectedDemandTypeId, (newVal, oldVal) => {
  onRefresh()
})

const banner = async () => {
  bannerList.value = await getBanner({ type: 1 })
}

banner()

emiter.on('like', (e: any) => {
  data.value.forEach((items: any) => {
    if (String(items.id) === e.id) {
      items.is_sign = e.is_sign
      if (String(e.is_sign) === '0') {
        items.sign_num -= 1
      } else {
        items.sign_num += 1
      }
    }
  })
})

// const closeDialog = () => {
//   regVisible.value = false
//   sessionStorage.setItem('temporary', '1')
// }

const infodetail = async (id: any) => {
}

const onRefresh = async () => {
  form.value.page = 1
  const list: any = await loadDemandList()
  data.value = list
  refreshing.value = false
}

const loadMore = async () => {
  form.value.page = form.value.page + 1
  const list: any = await loadDemandList()
  data.value = [...data.value, ...list]
  loading.value = false
}

const loadDemandList = async () => {
  // 异步更新数据
  const res: any =
    (await homeNews({ ...form.value })) || []
  if (!Array.isArray(res) && typeof res.list === 'object') {
    const keys: any = Object.keys(res.list)
    const newRes: any = keys.map((k: any) => res.list[k])
    finished.value = newRes.length < form.value.pageSize
    return newRes
  }
  finished.value = res.list.length < form.value.pageSize
  return res.list
}

onRefresh()

const news = async (id: any) => {
  router.push({ path: '/news', query: { id: id } })
}

const url = async (item: any) => {
  if (item.href) {
    window.location.href = item.href
  }
}

const onClickTab = async (item: string) => {
  router.push({ path: '/home', query: { type: item.name } })
}

</script>

<style lang="less" scoped>
// /deep/.van-tab--active {
//   font-size: var(--19) !important;
// }

// /deep/.van-tabs__nav {
//   display: initial;
//   margin: 0 15px;
// }

// /deep/.van-tab {
//   font-size: 14px;
//   margin-right: 32px;
//   display: inline-block;
// }

.home {
  padding: 0 0;

  .my-swipe {
    width: 340px;
    height: 146px;
    background: #ff7a1f;
    box-shadow: 0px 2px 10px 0px rgba(238, 150, 103, 0.5);
    border-radius: 5px;
    margin: 16px auto;

    img {
      width: 100%;
      height: 146px;
      object-fit: cover;
    }
  }

  .onSearch {
    border-radius: 5px;
    margin-bottom: 20px;

    .label_icon {
      overflow: hidden;
      display: flex;
      align-items: center;

      .icon {
        width: 34px;
        height: 34px;
        object-fit: cover;
        margin-right: 14px;
      }

      span {
        margin: 0 14px 0 0;
        color: #d8d8d8;
      }
    }

    .van-field__left-icon {
      display: none;
    }
  }
}

.content_box {

  // margin-top: 18px;
  .flex_box {
    margin: 15px;
    padding: 10px 10px;
    background-color: #fff;
    border-radius: 10px;
    border: 1px solid #f1f2f6;
  }

  .newsImg {
    width: 90%;
    margin: 15px auto;
  }

  .mation_box {
    display: flex;

    img {
      width: 112px;
      height: 86px;
      border-radius: 5px;
      object-fit: cover;
      margin-right: 13px;
    }

    p {
      line-height: 23px;
    }
  }

  .time_box {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 15px;

    .time {
      // margin-left: 4px;
    }

    .iconSvgBox {
      height: 13px;

      .iconSvg {
        width: 24px;
        height: 13px;
        // margin-right: 6px;
      }
    }
  }
}

.pub_tab {
  position: relative;

  .calendar {

    // width: 24px;
    // height: 24px;
    // position: absolute;
    // top: 0;
    // right: 0;
    // background: #f7f7f7;
    // z-index: 99999;
    .calendar_svg {
      // width: 100%;
      // height: 100%;
    }
  }
}

.tabbarW {
  width: 100%;
}

.TabbarSlide_head {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .TabbarSlide_svg {
    width: 20%;
    height: 40px;
    line-height: 50px;
    text-align: center;
    background-color: #fff;
  }

  .calendar_svg {
    margin-right: 15px;
    width: 20px;
    height: 20px;
  }
}

@media (min-width: 750px) {
  // /deep/.van-tab--active {
  //   font-size: var(--19) !important;
  // }

  // /deep/.van-tabs__nav {
  //   display: initial;
  //   margin: 0 15px;
  // }

  // /deep/.van-tab {
  //   font-size: 14px;
  //   margin-right: 32px;
  //   display: inline-block;
  // }

  .home {
    padding: 0 0;

    .my-swipe {
      width: 340px;
      height: 146px;
      background: #ff7a1f;
      box-shadow: 0px 2px 10px 0px rgba(238, 150, 103, 0.5);
      border-radius: 5px;
      margin: 16px auto;

      img {
        // width: 100%;
        height: 146px;
        object-fit: cover;
      }
    }

    .onSearch {
      border-radius: 5px;
      margin-bottom: 20px;

      .label_icon {
        overflow: hidden;
        display: flex;
        align-items: center;

        .icon {
          width: 34px;
          height: 34px;
          object-fit: cover;
          margin-right: 14px;
        }

        span {
          margin: 0 14px 0 0;
          color: #d8d8d8;
        }
      }

      .van-field__left-icon {
        display: none;
      }
    }
  }

  .content_box {

    // margin-top: 18px;
    .flex_box {
      margin: 15px;
      padding: 10px 10px;
      background-color: #fff;
      border-radius: 10px;
      border: 1px solid #f1f2f6;
    }

    .newsImg {
      width: 90%;
      margin: 15px auto;
    }

    .mation_box {
      display: flex;

      img {
        width: 112px;
        height: 86px;
        border-radius: 5px;
        object-fit: cover;
        margin-right: 13px;
      }

      p {
        line-height: 23px;
      }
    }

    .time_box {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 15px;

      .time {
        // margin-left: 4px;
      }

      .iconSvgBox {
        height: 13px;

        .iconSvg {
          width: 24px;
          height: 13px;
          // margin-right: 6px;
        }
      }
    }
  }

  .pub_tab {
    position: relative;

    .calendar {

      // width: 24px;
      // height: 24px;
      // position: absolute;
      // top: 0;
      // right: 0;
      // background: #f7f7f7;
      // z-index: 99999;
      .calendar_svg {
        // width: 100%;
        // height: 100%;
      }
    }
  }

  .tabbarW {
    width: 100%;
  }

  .TabbarSlide_head {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .TabbarSlide_svg {
      width: 20%;
      height: 40px;
      line-height: 50px;
      text-align: center;
      background-color: #fff;
    }

    .calendar_svg {
      margin-right: 15px;
      width: 20px;
      height: 20px;
    }
  }
}
</style>
